package com.bbs.toutiao.service.client.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.mapper.clinet.ClientArticleEditMapper;
import com.bbs.toutiao.mapper.clinet.ClientChatMapper;
import com.bbs.toutiao.mapper.clinet.ClientUserEditorMapper;
import com.bbs.toutiao.mapper.clinet.ClientUserMapper;
import com.bbs.toutiao.service.client.ClientUserHomeService;
import com.bbs.toutiao.vo.article.ArticlePageRequestVo;
import com.bbs.toutiao.vo.article.ArticleVo;
import com.bbs.toutiao.vo.client.ArticleUserVo;
import com.bbs.toutiao.vo.client.HistoryListVo;
import com.bbs.toutiao.vo.comm.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 描述:
 * 作者： zhangBin
 * 时间： 2024/3/3 22:10
 * 版本： 1.0
 */

@Slf4j
@Service
public class ClientUserHomeServiceImpl implements ClientUserHomeService {

    @Resource
    ClientUserMapper clientUserMapper;

    @Resource
    ClientArticleEditMapper articleEditMapper;

    @Resource
    ClientChatMapper chatMapper;

    @Resource
    ClientUserEditorMapper clientUserEditorMapper;


    /**
     * 查询用户主页
     *
     * @param userId
     * @return ArticleUserVo
     * @author zhangBin
     */
    @SysLog("用户查看某个用户主页")
    @Override
    public ArticleUserVo selectUserHome(int userId, int followingId) {
        // 查询用户主页的逻辑
        ArticleUserVo articleUserVo = clientUserMapper.selectByUserId(userId);
        long follows = clientUserMapper.followsCount(userId);
        long following = clientUserMapper.followingCount(userId);
        articleUserVo.setFollows(follows);
        articleUserVo.setFollowing(following);
        if (followingId > 0) {
            int i = chatMapper.followByUserIdFollowingId(userId, followingId);
            articleUserVo.setIsMutual(i);
        }
        return articleUserVo;
    }

    /**
     * 用户id查询关注者
     *
     * @param vo
     * @return
     */
    @Override
    public PageVo<ArticleVo> selectFollowsArticle(ArticlePageRequestVo vo) {
        //根据用户id查询被关注者的列表
        List<Integer> integers = clientUserMapper.selectFollowsByUserId(vo.getCreateUserId());
        if (integers.isEmpty()) {
            throw new BaseException(ExceptionEnum.NOT_FOLLOWS);
        }
        List<ArticleVo> articleVos = articleEditMapper.articlesFollowsUserId(integers, vo.getPage(), vo.getSize(), vo.getCreateUserId());
        for (ArticleVo ar : articleVos) {
            if (ar.getImg() != null && !ar.getImg().equals(" ")) {
                //将json字符串转为数组
                JSONArray objects = JSONUtil.parseArray(ar.getImg());
                List<String> list = JSONUtil.toList(objects, String.class);
                if (list.size() > 2) {
                    ar.setCoverImg(CollectionUtil.sub(list, 0, 3));
                } else {
                    ar.setCoverImg(CollectionUtil.sub(list, 0, 1));
                }
                ar.setImg(null);
            }
        }

        long sum = articleEditMapper.countByFollowsUserId(integers);
        PageVo<ArticleVo> page = new PageVo<>();
        page.setPageList(articleVos);
        page.setTotal(sum);
        return page;
    }

    //查询收藏者及其收藏列表
    @Override
    public PageVo<ArticleVo> selectFavorites(ArticlePageRequestVo vo) {
        //收藏的文章列表
        List<Integer> integers = clientUserMapper.selectFavoritesByUserId(vo.getCreateUserId());
//        System.out.println(integers+"用户收藏列表"+vo);
        List<ArticleVo> articleVos = articleEditMapper.articleByFavoritesArticleId(integers, vo.getPage(), vo.getSize(), vo.getCreateUserId());
//        System.out.println("查询到的长度："+integers);
        for (ArticleVo ar : articleVos) {
            if (ar.getImg() != null && !ar.getImg().equals(" ")) {
                //将json字符串转为数组
                JSONArray objects = JSONUtil.parseArray(ar.getImg());
                List<String> list = JSONUtil.toList(objects, String.class);
                ar.setCoverImg(CollectionUtil.sub(list, 0, 1));
                ar.setImg(null);
            }
        }
        //收藏夹总数
        long sum = articleEditMapper.favoritesCount(vo.getCreateUserId());
        PageVo<ArticleVo> page = new PageVo<>();
        page.setPageList(articleVos);
        page.setTotal(sum);
        return page;
    }

    /**
     * 描述：添加关注或者取消
     *
     * @param userId
     * @param followId
     * @param status
     * @return
     */

    @SysLog("关注用户或取消关注")
    @Override
    public int addFollows(int userId, int followId, int status) {
        int i;
        //添加关注 1
        if (status == 1) {
            i = clientUserEditorMapper.insertFollows(userId, followId);
        } else {
            // 取消关注
            i = clientUserEditorMapper.deleteFollows(userId, followId);
            if (i > 0) {
                throw new BaseException(ExceptionEnum.USER_FOLLOWS);
            }
        }

        return i;
    }

    /**
     * 描述：用户收藏或者取消收藏
     *
     * @param userId
     * @param articleId
     * @param status
     * @return
     */
    @SysLog("用户对文章进行了收藏操作")
    @Override
    public int addFavorites(int userId, int articleId, int status) {
        int i;
        //添加收藏 1
        if (status == 1) {
            i = clientUserEditorMapper.insertFavorites(userId, articleId);
        } else {
            //取消收藏
            i = clientUserEditorMapper.deleteFavorites(userId, articleId);
        }

        return i;
    }

    /**
     * 查询用户的历史记录
     *
     * @param page
     * @param size
     * @param userId
     */
    @SysLog("用户查询历史记录")
    @Override
    public Map<String, Object> selectHistory(int page, int size, int userId) {
        List<Map<String, Object>> historyListId = clientUserEditorMapper.selectHistoryListId(userId, page, size);
        long count = clientUserEditorMapper.selectHistoryListCount(userId);//统计总数
        if (historyListId.isEmpty()) {
            throw new BaseException(ExceptionEnum.NOT_FOUND);
        }
        List<Integer> articleListId = new ArrayList<>();
        historyListId.forEach(e -> {
            Object articleId = e.get("article_id");
            articleListId.add(Integer.valueOf(articleId.toString()));
        });

        List<ArticleVo> articleVoList = clientUserEditorMapper.selectHistory(articleListId, userId);

        // 使用HashMap存储列表，加快查找速度
        HashMap<Object, ArticleVo> articleVoMap = new HashMap<>();
        for (ArticleVo vo : articleVoList) {

            if (vo.getImg() != null && !vo.getImg().equals(" ")) {
                //将json字符串转为数组
                JSONArray objects = JSONUtil.parseArray(vo.getImg());
                List<String> list = JSONUtil.toList(objects, String.class);
                vo.setCoverImg(CollectionUtil.sub(list, 0, 1));
                vo.setImg(null);
            }
            // 将文章ID与对象本身关联起来
            articleVoMap.put(vo.getId(), vo);
        }
        List<HistoryListVo> voList = new ArrayList<>();

        // 遍历历史id列表
        for (Map<String, Object> map : historyListId) {
            // 从map中找出相同ID的项
            ArticleVo vo = articleVoMap.get(map.get("article_id"));
            // 获取日期
            String date = map.get("time").toString();

            // 检查是否已经为特定日期创建了HistoryListVo
            HistoryListVo checkedHistoryListVo = voList.stream()
                    .filter(historyListVo -> date.equals(historyListVo.getTime()))
                    .findFirst()
                    .orElse(null);
            // 如果不存在，则创建新的HistoryListVo并添加到列表
            if (checkedHistoryListVo == null) {
                checkedHistoryListVo = new HistoryListVo();
                checkedHistoryListVo.setTime(date);
                checkedHistoryListVo.setList(new ArrayList<>());
                voList.add(checkedHistoryListVo);
            }
            Map<String, Object> map1 = new HashMap<>();
            map1.put("hId", map.get("h_id"));
            if (vo == null) {
                ArticleVo vo1 = new ArticleVo();
                vo1.setStatus(404);
                vo1.setArticleTitle("该文章已被删除");
                map1.put("article", vo1);
            } else {
                map1.put("article", vo);
            }

            // 将历史记录添加到相应的列表中
            checkedHistoryListVo.getList().add(map1);
        }
        Map<String, Object> page2 = new HashMap<>();
        page2.put("total", count);
        page2.put("pageList", voList);
        return page2;
    }

    //删除历史记录
    @Override
    public int deleteHistory(int userId, List<Map<String, Object>> mapList) {
        List<Object> list = CollUtil.getFieldValues(mapList, "id");

        List<Integer> intList = CollUtil.newArrayList();
        for (Object obj : list) {
            int intValue = Convert.toInt(obj);
            intList.add(intValue);
        }
        int i = clientUserEditorMapper.deleteHistories(userId, intList);
        log.info("删除了{},{}", i, intList);
        return i;
    }


}
